//
// Created by YueChuan on 2023/3/10.
//

#include "userWidget.h"

#include <utility>
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include "talkTabWidget.h"

userWidget::userWidget(QString sendUid_, QString sendName_, QString _acceptUid, QString _acceptName,
                       const QString &_status, QWidget *parent) :
        sendUid(std::move(sendUid_)), sendName(std::move(sendName_)),
        acceptUid(std::move(_acceptUid)), acceptName(std::move(_acceptName)) {
    if (_status == 1)
        status = true;
    else
        status = false;
    this->setMaximumSize(170, 80);
    this->setMinimumSize(170, 80);
    userName = new QLabel(this);
    upFileCount = new QLabel(this);
    state = new QLabel(this);

    // 设置状态、上传文件数目、在线状态
    //TODO: 上线状态能否实时更新到每个用户界面上?
    userName->setText("userName: " + acceptName);
    upFileCount->setText("uploadFile: null");
    if (status)
        state->setText("status: on-line");
    else
        state->setText("status: off-line");

    layout = new QGridLayout(this);

    layout->addWidget(userName, 0, 0);
    layout->addWidget(upFileCount, 1, 0);
    layout->addWidget(state, 2, 0);
    this->setLayout(layout);

}


void userWidget::mouseDoubleClickEvent(QMouseEvent * event) {
    auto widget = (MainWindow *) this->nativeParentWidget();
    widget->ui->tabWidget->setCurrentIndex(1);
    auto pTalkTabWidget = (talkTabWidget *) widget->ui->tabWidget->currentWidget();
    pTalkTabWidget->setSendUid(sendUid);
    pTalkTabWidget->setAcceptUid(acceptUid);
    pTalkTabWidget->setSendName(sendName);
    pTalkTabWidget->setAcceptName(acceptName);


    pTalkTabWidget->clearBrowser();
    pTalkTabWidget->showHistory();

    // 为了方式用户双击同一个用户多次，与服务器建立多个连接
    if (this->sendName + "与" + this->acceptName + "的对话" == widget->windowTitle()) {
        return;
    }
    widget->setWindowTitle(this->sendName + "与" + this->acceptName + "的对话");
    socket = new connectSocket(sendUid.toInt(), acceptUid.toInt());
    pTalkTabWidget->setSocket(socket);
}

void userWidget::disconnectSocket() {
    if (socket) {
        socket->disconnectSocket();
        socket = nullptr;
        delete socket;
    } else
        qDebug() << " socket has not construct";
}

userWidget::userWidget(QWidget * parent) {}


